package com.yanqu.road.server.manger;

import com.yanqu.road.dao.impl.servercenter.H5AppletUrlDaoImpl;
import com.yanqu.road.entity.servercenter.H5AppletUrl;
import com.yanqu.road.server.TempMgr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class H5AppletUrlMgr extends TempMgr {

    private static Map<String, List<H5AppletUrl>> h5AppletUrlMap = new ConcurrentHashMap<>();


    public static String getH5Url(String userId, int platform) {
        if (userId == null) {
            return getDefaultUrl(platform);
        }
        List<H5AppletUrl> urlList = h5AppletUrlMap.get(userId);
        if (urlList == null) {
            return getDefaultUrl(platform);
        }
        for (H5AppletUrl h5AppletUrl : urlList) {
            if (h5AppletUrl.getPlatform() == platform) {
                return h5AppletUrl.getUrl();
            }
        }
        return getDefaultUrl(platform);
    }

    public static String getDefaultUrl(int platform) {
        for (List<H5AppletUrl> urlList : new ArrayList<>(h5AppletUrlMap.values())) {
            for (H5AppletUrl url : urlList) {
                if (url.getType() == 1 && url.getPlatform() == platform) {
                    return url.getUrl();
                }
            }
        }
        return "";
    }


    @Override
    public boolean reloadConfig() throws Exception {
        h5AppletUrlMap = new ConcurrentHashMap<>();
        List<H5AppletUrl> urlList = new H5AppletUrlDaoImpl().getH5AppletUrlDaoImpl();
        for (H5AppletUrl h5AppletUrl : urlList) {
            String str = h5AppletUrl.getUserId();
            int type = h5AppletUrl.getType();
            int platform = h5AppletUrl.getPlatform();
            for (String userId : str.split(",")) {
                if (!h5AppletUrlMap.containsKey(userId)) {
                    h5AppletUrlMap.put(userId, new ArrayList<>());
                }
                List<H5AppletUrl> list = h5AppletUrlMap.get(userId);
                list.add(h5AppletUrl);
            }
        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return true;
    }
}
